package com.example.demo.service.impl;

import com.example.demo.entity.Instorage;
import com.example.demo.entity.Outstorage;
import com.example.demo.mapper.InstorageMapper;
import com.example.demo.mapper.OutstorageMapper;
import com.example.demo.service.StorageFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Service
public class StorageFeeServiceImpl implements StorageFeeService {

    @Autowired
    private InstorageMapper instorageMapper;

    @Autowired
    private OutstorageMapper outstorageMapper;

    @Override
    public double calculateStorageFee(Outstorage outstorage) throws ParseException {
        List<Instorage> instorages = instorageMapper.findInstoragesByStorageId(outstorage.getOsbelong());
        double cost = 0;
        double outWeight = outstorage.getOweight();

        for (Instorage instorage : instorages) {
            double realWeight = instorageMapper.findRealWeight(instorage.getIid());

            if (outWeight == 0) break;
            if (realWeight == 0) continue;

            double inWeight = realWeight;

            if (inWeight < outWeight) {
                outWeight -= inWeight;
                double temp = inWeight;
                inWeight = 0;
                instorageMapper.updateRealWeight(instorage.getIid(), inWeight);
                long days = getIntervalDays(instorage.getItime(), outstorage.getOtime());

                if (days >= 15) {
                    cost += temp * 0.5 * (days - 14);
                }
            } else {
                double temp = outWeight;
                inWeight -= temp;
                outWeight = 0;
                instorageMapper.updateRealWeight(instorage.getIid(), inWeight);
                long days = getIntervalDays(instorage.getItime(), outstorage.getOtime());

                if (days >= 15) {
                    cost += temp * 0.5 * (days - 14);
                }
            }
        }

        // 更新出库记录的堆存费
        outstorage.setOfee(cost);
        outstorageMapper.updateStorageFee(outstorage.getOid(), cost);

        return cost;
    }

    private long getIntervalDays(Date startDate, Date endDate) {
        long diff = endDate.getTime() - startDate.getTime();
        return diff / (1000 * 60 * 60 * 24);
    }
}